import { Body, Controller, Post, Res, HttpStatus } from '@nestjs/common';
import { UserService } from '../../user.service';
import { Response } from 'express';
import { ApiResponse, ApiTags } from '@nestjs/swagger';
import {
  LoginResSuccessDto,
  LoginResFailDto,
  LoginReqDto,
} from '../../dto/user.controller.dto';

@ApiTags('user')
@Controller('user')
export class LoginController {
  constructor(private readonly userService: UserService) {}
  @ApiResponse({
    description: '登录成功',
    type: LoginResSuccessDto,
    status: HttpStatus.OK,
  })
  @ApiResponse({
    description: '服务器内部错误',
    type: LoginResFailDto,
    status: HttpStatus.INTERNAL_SERVER_ERROR,
  })
  @Post('auth/login')
  async login(
    @Body() loginReqDto: LoginReqDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    let token: string;
    let success: boolean;
    let message: string;
    try {
      const { js_code } = loginReqDto;
      token = await this.userService.login(js_code);
      success = true;
      res.status(HttpStatus.OK);
    } catch (err) {
      console.log(err);
      success = false;
      message = '服务器内部错误';
      res.status(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return {
      success,
      token,
      message,
    };
  }
}
